#!/bin/bash
# deploy_app.sh 脚本内容

# 从CodePipeline环境变量获取镜像信息
ACR_REGION="${ACR_REGION_DEPLOY}"
ACR_NAMESPACE="${ACR_NAMESPACE_DEPLOY}"
IMAGE_NAME="${IMAGE_NAME_DEPLOY}"
IMAGE_TAG="${PIPELINE_COMMIT_ID}" 

CONTAINER_NAME="your-dotnet-app-container" # 您希望部署在ECS上的Docker容器名称
HOST_PORT="80" # 您的应用在ECS实例上对外暴露的端口
CONTAINER_PORT="80" # 您的.NET Core应用在Docker容器内部监听的端口

FULL_IMAGE_NAME="registry.${ACR_REGION}.aliyuncs.com/${ACR_NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"

echo "--- 部署开始 ---"

# 如果ECS实例没有绑定具有ACR拉取权限的RAM角色，取消注释以下行
# ACR_USERNAME_DEPLOY="${ACR_USERNAME_DEPLOY}"
# ACR_PASSWORD_DEPLOY="${ACR_PASSWORD_DEPLOY}"
# echo "${ACR_PASSWORD_DEPLOY}" | docker login --username=${ACR_USERNAME_DEPLOY} registry.${ACR_REGION_DEPLOY}.aliyuncs.com --password-stdin
# if [ $? -ne 0 ]; then
#   echo "ACR login failed on ECS! Check ECS network, ACR credentials, or RAM role."
#   exit 1
# fi
# echo "ACR login successful on ECS."

echo "Stopping and removing old container if exists..."
docker stop ${CONTAINER_NAME} || true
docker rm ${CONTAINER_NAME} || true
echo "Old container clean-up complete."

echo "Pulling new image: ${FULL_IMAGE_NAME}"
docker pull ${FULL_IMAGE_NAME}
if [ $? -ne 0 ]; then
  echo "Image pull failed! Check image name/tag, ACR permissions, or network connectivity on ECS."
  exit 1
fi
echo "Image pulled successfully."

echo "Running new container: ${CONTAINER_NAME}"
docker run -d \
  --name ${CONTAINER_NAME} \
  -p ${HOST_PORT}:${CONTAINER_PORT} \
  --restart=always \
  ${FULL_IMAGE_NAME}

if [ $? -ne 0 ]; then
  echo "Container run failed! Check container logs on ECS for details (docker logs ${CONTAINER_NAME})."
  exit 1
fi
echo "New container ${CONTAINER_NAME} started on port ${HOST_PORT}."

echo "--- 部署完成 ---"